<?php
namespace app\common;

/**
 * Description of Array
 *
 * @author wang
 */
class ArrayHelper extends \yii\helpers\ArrayHelper
{
    /**
     * ------------------------------------------
     * 把返回的数据集转换成Tree
     * @param array $list 要转换的数据集
     * @param string $pk 主键
     * @param string $pid parent标记字段
     * @param string $child
     * @param int $root
     * @return array
     * ------------------------------------------
     */
    public static function list_to_tree($list, $pk='id', $pid = 'pid', $child = 'childItem', $root = 0) {
        // 创建Tree
        $tree = [];
        if(is_array($list)) {
            // 创建基于主键的数组引用
            $refer = array();
            foreach ($list as $key => $data) {
                $refer[$data[$pk]] =& $list[$key];
            }
            foreach ($list as $key => $data) {
                // 判断是否存在parent
                $parentId =  $data[$pid];
                if ($root == $parentId) {
                    $tree[] =& $list[$key];
                    $list[$key][$child] = [];
                }else{
                    if (isset($refer[$parentId])) {
                        $parent =& $refer[$parentId];
                        $parent[$child][] =& $list[$key];
                        if($data['type']!='courseItemType.section')
                        {
                            $list[$key][$child] = [];
                        }
                    }
                }
            }
        }
        return $tree;
    }

    /**
     * ------------------------------------------
     * 二维数组排序(有键值)
     * @param array $arr 要排序的数据集
     * @param string $keys 指定的键值
     * @param string $type asc正序 desc倒序
     * @return array
     * ------------------------------------------
     */
    public static function array_sort($arr,$keys,$type='desc'){
        $keysvalue = $new_array = array();
        foreach ($arr as $k=>$v){
            $keysvalue[$k] = $v[$keys];
        }
        if($type == 'asc'){
            asort($keysvalue);
        }else{
            arsort($keysvalue);
        }
        reset($keysvalue);
        foreach ($keysvalue as $k=>$v){
            $new_array[] =& $arr[$k];
        }
        return $new_array;
    }
    /**
     * mysql 查询出的数组 null 转 ''
     * @param type $arr
     * @return type
     */
    public static function array_is_null($arr){
        $new_array = array();
        if(count($arr) == count($arr,1)){
            foreach ($arr as $key =>$a){
                $new_array[$key] = $a===NULL?'':$a;
            }
            return $new_array;
        }else{
            foreach ($arr as $key =>$a){
                foreach ($a as $k => $val) {
                    $new_array[$key][$k] = $val===NULL?'':$val;
                }
            }
            return $new_array;
        }
    }
    public static function change_to_quotes($str) {
        return sprintf("'%s'", $str);
    }
}
